package com.lty.mp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.lty.mp.dao.UserDao;
import com.lty.mp.entity.User;
import com.lty.mp.utils.ResponseInfo;
import com.lty.mp.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author LTY
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private final UserDao userDao;

    @Autowired
    public UserController(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * 方法一：new对象，修改字段少，但没有锁
     *
     * @return
     */
    @RequestMapping("/update1/{age}/{delay}")
    public ResponseInfo update1(@PathVariable Integer age, @PathVariable Integer delay) {
        Long id = 6L;

        // 1、new一个对象
        User userBefore = userDao.selectById(id);
        User user = new User();
        user.setId(id);
        user.setAge(age);
        try {
            Thread.sleep(delay * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count1 = userDao.updateById(user);
        User userRtn = userDao.selectById(id);

        if (count1 == 1) {
            log.info("\n根据主键更新成功，before>>>{}， after>>>{}", userBefore, userRtn);
            return ResponseUtil.success("根据主键更新成功", userRtn);
        } else {
            return ResponseUtil.error("失败");
        }

    }

    /**
     * 方法二：查询记录，然后进行修改，修改每个字段，但是有锁
     */
    @RequestMapping("/update2/{age}/{delay}")
    public ResponseInfo update2(@PathVariable Integer age, @PathVariable Integer delay) {
        Long id = 6L;

        // 2、数据库中查找一条记录
        User userBefore = Optional.ofNullable(userDao.selectById(id)).orElseThrow(() -> new RuntimeException("请检查查询条件"));
        User updateUser = new User();
        BeanUtils.copyProperties(userBefore, updateUser);
        updateUser.setAge(age);
        try {
            Thread.sleep(delay * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count2 = userDao.updateById(updateUser);
        User userAfter = userDao.selectById(id);
        if (count2 == 1) {
            log.info("\n根据主键更新成功，before>>>{}， after>>>{}", userBefore, userAfter);
            return ResponseUtil.success("根据主键更新成功", userAfter);
        } else {
            return ResponseUtil.error("失败");
        }

    }
}
